package edu.wtbu.cs.androiddemo.activity.store;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import edu.wtbu.cs.androiddemo.R;

public class FileStoreSampleActivity extends AppCompatActivity {

    private EditText editText;
    private TextView textView;
    private Button buttonSave;
    private Button buttonRead;
    private String fileName = "content.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_file_store_sample);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initView();

    }

    private void initView() {
        editText = (EditText) findViewById(R.id.edit_content);
        textView = (TextView) findViewById(R.id.tv_content);
        buttonSave = (Button) findViewById(R.id.btn_save);
        buttonRead = (Button) findViewById(R.id.btn_read);
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = editText.getText().toString();
                try {
                    FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
                    fos.write(content.getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileInputStream fis = openFileInput(fileName);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);
                    String content = new String(bytes);
                    textView.setText(content);
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}